package lichtruong.bk.cse;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

	int back;
	Intent getback;
	Button btLogin, cancel;
	ProgressDialog pDialog;
	EditText mail_login, password_login;
	JSONParser JsonParser = new JSONParser();
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_MESSAGE = "message";
	private static final String REGISTER_URL = "http://lichcse.hol.es/login.php";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		getback = getIntent();
		back = Integer.parseInt(getback.getStringExtra("back"));
		btLogin = (Button) findViewById(R.id.btLogin);
		cancel = (Button) findViewById(R.id.cancel);
		mail_login = (EditText) findViewById(R.id.mail_login);
		password_login = (EditText) findViewById(R.id.password_login);

		btLogin.setOnClickListener(this);
		cancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btLogin:
			switch (checkInputData()) {
			case 0:
				new CreateUser().execute();
				break;
			case 1:
				Toast.makeText(getBaseContext(),
						"Please Enter Both a Mail and Password .",
						Toast.LENGTH_LONG).show();
				break;
			case 2:
				Toast.makeText(getBaseContext(), "Please check mail . . .",
						Toast.LENGTH_LONG).show();
				break;
			}
			break;

		case R.id.cancel:
			this.finish();
			break;
		}
	}

	class CreateUser extends AsyncTask<String, String, String> {
		int success;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Login.this);
			pDialog.setMessage("Please wait login ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			// Check for success tag
			String mail = mail_login.getText().toString();
			String password = password_login.getText().toString();
			try {
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("mail", mail));
				params.add(new BasicNameValuePair("password", password));

				Log.d("request!", "starting");

				// Posting user data to script
				JSONObject json = JsonParser.makeHttpRequest(REGISTER_URL,
						"POST", params);

				// full json response
				Log.d("Registering attempt", json.toString());

				// json success element
				success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					Log.d("User Created!", json.toString());
					finish();
					return json.getString(TAG_MESSAGE);
				} else {
					Log.d("Đăng Nhập Thất Bại", json.getString(TAG_MESSAGE));
					return json.getString(TAG_MESSAGE);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog once product deleted
			pDialog.dismiss();
			if(success == 1){
				Database updateMail = new Database(Login.this);
				updateMail.open();
				if(updateMail.getData_USER().mail != mail_login.getText().toString()){
					updateMail.updateUser(mail_login.getText().toString(),password_login.getText().toString(), "1");
				}
				updateMail.close();
				
				if (file_url != null) {
					Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
				}
				Thread timer = new Thread() {
					public void run() {
						try {
							sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						} finally {
							if(back == 1){
								Intent menu = new Intent(Login.this, lichtruong.bk.cse.menu.class);
								startActivity(menu);
							}
							if(back == 2){
								Intent menu = new Intent(Login.this, lichtruong.bk.cse.Report.class);
								startActivity(menu);
							}
							if(back == 3){
								Intent menu = new Intent(Login.this, lichtruong.bk.cse.GetDataReported.class);
								startActivity(menu);
							}
							if(back == 4){
								Intent autoget = new Intent(Login.this, lichtruong.bk.cse.AuToGet.class);
								startActivity(autoget);
							}
						}
					}
				};
				timer.start();
			}
		}
	}

	public int checkInputData() {
		int len_mail = mail_login.getText().toString().length();
		int len_pass = password_login.getText().toString().length();

		if (len_mail == 0 || len_pass == 0) {
			return 1;
		} else if (!checkMailRegister(mail_login.getText().toString())) {
			return 2;
		} else {
			return 0;
		}
	}

	public boolean checkMailRegister(String mail) {
		Pattern pattern;
		Matcher matcher;
		final String MAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(MAIL_PATTERN);
		matcher = pattern.matcher(mail);
		return matcher.matches();
	}

}
